package com.taotao.product.controller;

import com.taotao.common.core.domain.Result;
import com.taotao.common.core.utils.poi.ExcelUtil;
import com.taotao.common.core.web.controller.BaseController;
import com.taotao.common.core.web.page.TableDataInfo;
import com.taotao.common.log.annotation.Log;
import com.taotao.common.log.enums.BusinessType;
import com.taotao.common.redis.service.RedisService;
import com.taotao.common.security.annotation.RequiresPermissions;
import com.taotao.product.domain.PmsSkuInfo;
import com.taotao.product.domain.SkuInventoryQuantity;
import com.taotao.product.service.IPmsSkuInfoService;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * sku信息Controller
 *
 * @author ccy
 * @date 2024-01-16
 */
@RestController
@RequestMapping("/skuinfo")
@Slf4j
public class PmsSkuInfoController extends BaseController
{
    @Autowired
    private IPmsSkuInfoService pmsSkuInfoService;

    @Autowired
    private RedisService redisService;


    private final String SKU_INFO_KEY="skuInfo:";
    /**
     * 查询sku信息列表
     */
    @RequiresPermissions("product:skuinfo:list")
    @GetMapping("/list")
    public Result<TableDataInfo> list(PmsSkuInfo pmsSkuInfo)
    {
        startPage();
        List<PmsSkuInfo> list = pmsSkuInfoService.selectPmsSkuInfoList(pmsSkuInfo);
        return getDataTable(list);
    }

    /**
     * 导出sku信息列表
     */
    @RequiresPermissions("product:skuinfo:export")
    @Log(title = "sku信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PmsSkuInfo pmsSkuInfo)
    {
        List<PmsSkuInfo> list = pmsSkuInfoService.selectPmsSkuInfoList(pmsSkuInfo);
        ExcelUtil<PmsSkuInfo> util = new ExcelUtil<PmsSkuInfo>(PmsSkuInfo.class);
        util.exportExcel(response, list, "sku信息数据");
    }

    /**
     * 获取sku信息详细信息
     */
    @RequiresPermissions("product:skuinfo:query")
    @GetMapping(value = "/{skuId}")
    public Result getInfo(@PathVariable("skuId") Long skuId)
    {
        return success(pmsSkuInfoService.selectPmsSkuInfoBySkuId(skuId));
    }

    /**
     * 新增sku信息
     */
    @RequiresPermissions("product:skuinfo:add")
    @Log(title = "sku信息", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@RequestBody PmsSkuInfo pmsSkuInfo)
    {
        return toAjax(pmsSkuInfoService.insertPmsSkuInfo(pmsSkuInfo));
    }

    /**
     * 修改sku信息
     */
    @RequiresPermissions("product:skuinfo:edit")
    @Log(title = "sku信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@RequestBody PmsSkuInfo pmsSkuInfo)
    {
        return toAjax(pmsSkuInfoService.updatePmsSkuInfo(pmsSkuInfo));
    }

    /**
     * 删除sku信息
     */
    @RequiresPermissions("product:skuinfo:remove")
    @Log(title = "sku信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{skuIds}")
    public Result remove(@PathVariable Long[] skuIds)
    {
        return toAjax(pmsSkuInfoService.deletePmsSkuInfoBySkuIds(skuIds));
    }


    /**
    * @Author ZhangYuQi
    * @Description 根据skuIds查询对应的商户id
    * @Date 下午10:08 2024/12/27
    * @Param [skuIds]
    * @return
    */
    @GetMapping("selectMerchantIdsBySkuIds/{skuId}")
    public Result<Long> selectMerchantIdsBySkuIds(@PathVariable("skuId") Long skuId)
    {
    	Long merchantId = pmsSkuInfoService.selectMerchantIdsBySkuIds(skuId);
    	return Result.success(merchantId);
    }

    /**
    * @Author ZhangYuQi
    * @Description 库存预热 项目启动时将sku对应的库存存入到redis
    * @Date 上午10:15 2025/2/6
    * @Param
    * @return
    */
    @PostConstruct
    public void init() {
        log.info("商品服务启动成功,开始预热sku库存信息");
        //先清空redis中的数据
        redisService.deleteObject(SKU_INFO_KEY);

        List<PmsSkuInfo> skus=pmsSkuInfoService.selectSkuInventoryQuantity();
        if(skus.size()==0){
            //如果不存在库存信息，则将redis中的数据设置为null 防止穿透
            redisService.setCacheObject(SKU_INFO_KEY+null,null);
        }else{
            //遍历 以skuId为key，库存为value
            skus.forEach(sku->{
                // 如果库存为0，也显式设置为0
                int inventoryQuantity = sku.getInventoryQuantity() == null ? 0 : sku.getInventoryQuantity();
                //随机生成过期时间 防止雪崩
                //long expireTime=(long)(Math.random()*1000)+1000;
                //redisService.setCacheObject(SKU_INFO_KEY+sku.getSkuId(),inventoryQuantity,expireTime, TimeUnit.SECONDS);
                redisService.setCacheObject(SKU_INFO_KEY+sku.getSkuId(),inventoryQuantity);
            });
        }
        log.info("预热sku库存信息成功");
    }

    /**
    * @Author ZhangYuQi
    * @Description 批量同步商品库存
    * @Date 上午12:48 2025/2/10
    * @Param [skuIds]
    * @return
    */
    @PostMapping("/decrInventory")
    public Result decrInventory(@RequestBody List<SkuInventoryQuantity> skuInventoryQuantities) {
        pmsSkuInfoService.decrInventory(skuInventoryQuantities);
        return Result.success();
    }




}
